package com.aos.erp.schools.service.common.impl;

import com.aos.erp.schools.mapper.common.RegionMapper;
import com.aos.erp.schools.mapper.sys.UserMapper;
import com.aos.erp.schools.model.common.Region;
import com.aos.erp.schools.model.common.vo.RegionTree;
import com.aos.erp.schools.model.common.vo.RegionVo;
import com.aos.erp.schools.model.sys.User;
import com.aos.erp.schools.model.sys.vo.MenuTree;
import com.aos.erp.schools.model.sys.vo.MenuVo;
import com.aos.erp.schools.service.common.RegionService;
import com.aos.erp.schools.service.sys.UserService;
import com.aos.erp.schools.util.TreeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: erp
 * @description: 区域字典service
 * @author: tanzhiyu
 * @create: 2018-11-09 17:48
 **/
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    @Resource
    private RegionMapper regionMapper;

    public List<Region> findByParams(Map<String, Object> map) {
        return regionMapper.findByParams(map);
    }

    /**
     * 获取组织树
     *
     * @return
     * @throws Exception
     */
    public List<RegionTree> selectTree() throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<Region> regions = regionMapper.findByParams(params);
        if (regions == null || regions.size() == 0) {
            return new ArrayList<RegionTree>();
        }
        return getMenuTree(regions, regions.get(0).getParentId());
    }

    private List<RegionTree> getMenuTree(List<Region> menus, Long root) {
        List<RegionTree> trees = new ArrayList<RegionTree>();
        RegionTree node = null;
        for (Region menu : menus) {
            node = new RegionTree();
            BeanUtils.copyProperties(menu, node);
            trees.add(node);
        }
        return TreeUtil.bulid(trees, root);
    }

    public List<RegionVo> findByParamsParentId(Map<String, Object> map) {
        return regionMapper.findByParamsParentId(map);
    }

    /**
     * 根据code查询下级信息
     *
     * @param code
     * @return
     */
    public List<Region> findByParamsCode(String code) {
        return regionMapper.findByParamsCode(code);
    }
}
